package com.conduit.reporter.client;

import org.json.JSONObject;

public class ConduitReporterClient  {
	private static final String RESULT_STRING = "RESULT";
	public static final CharSequence ERROR_STRING = "ERROR";
	public static final CharSequence SUCCESS_STRING = "SUCCESS";
	public static final String NO_DATA_STRING = "NO_DATA_FROM_SERVER";

	private TcpClient tcpClient;
	private static int port = 4321;
	private static String host = "localhost";

	
	
	public ConduitReporterClient(String host, int port) {
		try {
			tcpClient = new TcpClient(host, port);
		} catch (Exception e) {
		}
	}

	/**
	 * Send data using the TCP connection & wait for response Parse the response (make conversions if necessary - pixels
	 * to mms) and report
	 * 
	 * @param device
	 * @param data
	 *            serialised JSON object
	 * @throws Exception
	 */
	public String sendData(String command, String... params) throws Exception {
		String resultValue;
		try {
			JSONObject result = sendDataAndGetJSonObj(command, params);

			if (result.isNull(RESULT_STRING)) {
				return NO_DATA_STRING;
			}
			resultValue = (String) result.get(RESULT_STRING);
			if (resultValue.contains(ERROR_STRING)) {
//				logger.error(result);
//				device.getScreenshot(null);
			} else if (resultValue.contains(SUCCESS_STRING)) {
//				logger.info(result);
			}

		} catch (Exception e) {
//			logger.error("Failed to send / receive data", e);
			throw e;
		}
//		if (getScreenshots) {
//			device.getScreenshot(null);
//		}
		return resultValue;
	}

	public JSONObject sendDataAndGetJSonObj(String command, String... params) throws Exception {
		JSONObject jsonobj = new JSONObject();
		jsonobj.put("Command", command);
		jsonobj.put("Params", params);
//		logger.info("Sending command: " + jsonobj.toString());
		JSONObject result = null;
//		logger.info("Send Data to " + device.getSerialNumber());

		try {
			String resultStr = null;
			if ((resultStr = tcpClient.sendData(jsonobj)) == null) {
				throw new Exception("No data recvied from server! pleas check server log!");
			}
			result = new JSONObject(resultStr);
		} catch (Exception e) {
//			logger.error("Failed to send / receive data", e);
			throw e;
		}
		return result;
	}

//	
//	public byte[] pull(String fileName) throws Exception {
//		JSONObject jsonObj = sendDataAndGetJSonObj("pull", fileName);
////		logger.info("command pull receved" + jsonObj);
//		return ((jsonObj.getString("file"))).getBytes("UTF-16LE");
//	}

//	public String push(byte[] data, String newlocalFileName) throws Exception {
//		String result = sendData("createFileInServer", newlocalFileName, Base64.encodeBytes(data, Base64.URL_SAFE), "true");
//		return result;
//	}


}
